#include "simulation_service.h"

namespace application {
namespace simulation {

SimulationService::SimulationService(
    std::shared_ptr<MapApplicationService> mapService,
    std::shared_ptr<kernel::ILogger> logger,
    QObject* parent)
    : QObject(parent)
    , m_logger(logger)
    , m_engine(std::make_unique<SimulationEngine>(mapService, logger, this))
    , m_enabled(false)
{
    // 连接引擎信号
    connect(m_engine.get(), &SimulationEngine::simulationStarted,
            this, [this]() {
        emit simulationStateChanged(true, false);
    });

    connect(m_engine.get(), &SimulationEngine::simulationPaused,
            this, [this]() {
        emit simulationStateChanged(true, true);
    });

    connect(m_engine.get(), &SimulationEngine::simulationResumed,
            this, [this]() {
        emit simulationStateChanged(true, false);
    });

    connect(m_engine.get(), &SimulationEngine::simulationStopped,
            this, [this]() {
        emit simulationStateChanged(false, false);
    });
}

bool SimulationService::initialize() {
    if (!m_enabled) {
        if (m_logger) {
            m_logger->info("仿真服务未启用");
        }
        return true;
    }

    m_engine->init();

    if (m_logger) {
        m_logger->info("仿真服务初始化完成");
    }

    return true;
}

void SimulationService::play() {
    if (m_enabled) {
        m_engine->play();
    }
}

void SimulationService::pause() {
    if (m_enabled) {
        m_engine->pause();
    }
}

void SimulationService::resume() {
    if (m_enabled) {
        m_engine->resume();
    }
}

void SimulationService::stop() {
    if (m_enabled) {
        m_engine->stop();
    }
}

void SimulationService::step(double deltaTime) {
    if (m_enabled) {
        m_engine->step(deltaTime);
    }
}

void SimulationService::setTimeScale(double scale) {
    if (m_enabled) {
        m_engine->setTimeScale(scale);
    }
}

double SimulationService::getSimulationTime() const {
    if (m_enabled) {
        return m_engine->getSimulationTime();
    }
    return 0.0;
}

void SimulationService::recordInitialVehicleState(int agvNumber, const QString& station, const QString& map) {
    m_initialVehicleStates.insert(agvNumber, SimulationVehicleState{station, map});
}

void SimulationService::resetVehiclesToInitialState() {
    if (!m_enabled || !m_engine || !m_engine->physicsSimulator()) {
        if (m_logger) {
            m_logger->warning("仿真服务未启用或物理模拟器不可用，无法执行重置");
        }
        return;
    }

    for (auto it = m_initialVehicleStates.constBegin(); it != m_initialVehicleStates.constEnd(); ++it) {
        const int agvNumber = it.key();
        const auto& state = it.value();
        m_engine->physicsSimulator()->registerVehicle(
            agvNumber,
            state.station.toStdString(),
            state.map.toStdString());
    }

    if (m_logger) {
        m_logger->info("已根据配置重置所有仿真车辆的位置");
    }
}

} // namespace simulation
} // namespace application
